<script setup>
import { ref, computed } from 'vue'


const visible = ref(false);
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  regions: {
    type: Array,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'save'])

const dialogVisible = computed({
  get() {
    return props.modelValue
  },
  set(value) {
    emit('update:modelValue', value)
  }
})

const selectedRegions = ref({})

const regionGroups = computed(() => {
  const groups = {}
  props.regions.forEach(region => {
    if (!groups[region.group]) {
      groups[region.group] = []
    }
    groups[region.group].push(region)
  })
  return groups
})

const handleCancel = () => {
  dialogVisible.value = false
}

const handleSave = () => {
  const selected = Object.values(selectedRegions.value).flat()
  emit('save', selected)
  dialogVisible.value = false
}
</script>

<template>
  <el-dialog v-model="dialogVisible" title="选择区域" width="80%">
    <div class="region-selector">
      <div v-for="(group, groupName) in regionGroups" :key="groupName" class="region-group">
        <div class="group-title">{{ groupName }}:</div>
        <el-checkbox-group v-model="selectedRegions[groupName]">
          <el-checkbox v-for="region in group" :key="region.id" :label="region.id">{{ region.name }}</el-checkbox>
        </el-checkbox-group>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.region-selector {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.region-group {
  display: flex;
  align-items: center;
}

.group-title {
  margin-right: 1rem;
  font-weight: bold;
}
</style>